<template>
  <div class="container">
    <div class="content box-item">
      <!-- 基本信息 -->
      <div class="card-title">计划信息</div>
      <div class="base-info">
        <el-form :model="baseForm" label-width="auto" label-position="top" ref="baseFormRef" :rules="baseFormRules">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="采购计划单号" prop="number">
                <el-input v-model="baseForm.number" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购计划标题" prop="name">
                <el-input v-model="baseForm.name" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购类型" prop="type">
                <el-select v-model="baseForm.type" style="width: 100%" placeholder="请选择项目类型">
                  <el-option :label="item.label" :value="item.label" v-for="(item, index) in procurementTypeOptions" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="采购控制总金额(￥)">
                <el-input v-model="baseForm.totalAmount" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建人" prop="userName">
                <el-input v-model="baseForm.userName" placeholder="请输入创建人" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="申请时间">
                <el-input v-model="baseForm.createTime" placeholder="提交后自动生成当前时间" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="18">
              <el-form-item label="采购说明">
                <el-input v-model="baseForm.illustrate" type="textarea" placeholder="请输入采购说明" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!-- 根据步骤显示 -->
    <div class="content box-item">
      <!-- 1招标立项 -->
      <ProjectStep1 :baseForm="baseForm" :id="id" :hideTab2="true" />
    </div>
    <div class="fixed-btns">
      <div class="btns" v-if="pageType == 1">
        <template v-if="[0, 3].includes(baseForm.state)">
          <el-button type="primary" @click="handleSave(1)">保存</el-button>
          <el-button type="primary" @click="handleSave(2)">提交</el-button>
        </template>
        <el-button @click="handleGoBack">退出</el-button>
      </div>
      <div class="btns" v-if="pageType == 2">
        <el-button type="primary" @click="handleEdit('state', 2)">通过</el-button>
        <el-button type @click="handleEdit('state', 3)">不通过</el-button>
        <el-button @click="handleGoBack">退出</el-button>
      </div>
      <div class="btns">
        <el-button type="danger" v-if="baseForm.state != 4 && pageType == 2" @click="handleEdit('state', 4)">作废</el-button>
        <el-button type v-if="baseForm.state == 4 " @click="handleEdit('state', 0)">保存并恢复</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import ProjectStep1 from './components/ProjectStep1.vue'
import { biddingProcurementById, insertPlan, updatePlan, updatePlanState } from '@/api/bidding'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'

const store = useStore()
const userInfo = ref(store.state.base.userInfo)

const route = useRoute()
const router = useRouter()
const id = route.query.id // 获取当前路由的id参数
const pageType = route.query.pageType // pageType 1 查看 2 审核

const procurementTypeOptions = ref([
  { label: '服务性采购',  },
  { label: '项目性采购',  },
  { label: '一般用品采购',  },
])
// 基本信息
const baseFormRef = ref()
const baseFormRules = ref({
  number: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  name: [{ required: true, message: '请输入项目名称', trigger: 'change' }],
  userName: [{ required: true, message: '请输入', trigger: 'blur' }],
})
const defaultBaseForm = {
  number: '', //招标单号
  name: '', //项目名称
  totalAmount: 0, //采购控制总金额(￥)
  userName: '', //创建人
  createTime: '', //业务日期
  illustrate: '', //采购说明
  type: '', //采购类型
  procurementItemsInfoList: [], //采购明细
  state: 0, //状态 0 暂存 1 审核中 2 审核通过 3 审核不通过 4 作废
}
const generateTimeString = () => {
  var now = new Date()
  var year = now.getFullYear()
  var month = now.getMonth() + 1 // 月份是从0开始的
  var day = now.getDate()
  var hours = now.getHours()
  var minutes = now.getMinutes()
  var seconds = now.getSeconds()

  // 将月份、日期、小时、分钟和秒数转换为两位数的字符串
  month = month < 10 ? '0' + month : month
  day = day < 10 ? '0' + day : day
  hours = hours < 10 ? '0' + hours : hours
  minutes = minutes < 10 ? '0' + minutes : minutes
  seconds = seconds < 10 ? '0' + seconds : seconds

  // 拼接成所需格式的字符串
  var timeString = year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds

  return timeString
}
const baseForm = ref({})
const biddingProjectByIdAsync = async () => {
  if (id) {
    let res = await biddingProcurementById({ id })
    baseForm.value = res.data
  } else {
    //新增
    baseForm.value = structuredClone(defaultBaseForm)
    baseForm.value.userName = userInfo.value?.name ? userInfo.value.name : '--'
    baseForm.value.number = 'CGJH' + generateTimeString() + Math.floor(Math.random() * 10000)
  }
}
biddingProjectByIdAsync()

// 保存 提交
const handleSave = (type) => {
  baseFormRef.value.validate(async (valid) => {
    // 校验
    let indexText = []
    baseForm.value.procurementItemsInfoList.forEach((item, index) => {
      if (!item.name) {
        indexText.push(index + 1)
      }
    })
    if (indexText.length) {
      indexText.forEach((item) => {
        ElMessage({
          message: `第${item}行采购内容不能为空`,
          type: 'warning',
        })
      })
      return
    }
    if (valid) {
      if (type == 2) baseForm.value.state = 1
      let res = null
      if (id) {
        // 修改
        res = await updatePlan(baseForm.value)
      } else {
        // 新增
        res = await insertPlan(baseForm.value)
      }
      if (res.code === 20000) {
        ElMessage({
          message: '提交成功',
          type: 'success',
        })
      }
      handleGoBack()
    } else {
      return false
    }
  })
}
// 退出
const handleGoBack = () => {
  router.push({
    path: '/bidding/project/plan',
  })
}
// 审核
const handleEdit = (field, val) => {
  let text
  switch (val) {
    case 0:
      text = '恢复'
      break
    case 2:
      text = '通过'
      break
    case 3:
      text = '不通过'
      break
    case 4:
      text = '作废'
      break

    default:
      text = '操作'
      break
  }
  ElMessageBox.confirm(`<div><p style="font-size: 16px;margin-bottom: 15px;">是否确认${text}？</p></div>`, '操作确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    baseForm.value[field] = val
    let res = await updatePlanState({ id, state: val })
    if (res.code === 20000) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
      handleGoBack()
    }
  })
}
</script>
<style scoped lang='scss'>
.container {
  width: 100%;
  position: relative;
  .box-item {
    box-sizing: border-box;
    width: 100%;
    background-color: #fff;
    flex-shrink: 0;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    margin-right: 10px;
    border-radius: 8px;
    box-sizing: border-box;
    padding: 15px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-bottom: 15px;
  }
  .card-title {
    font-size: 18px;
    font-weight: bold;
    margin-right: 20px;
    margin-bottom: 15px;
  }
  .top-box {
    position: relative;
    .card-title {
      position: absolute;
      left: 15px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .steps {
    margin-top: 10px;
    display: flex;
    justify-content: center;
    .desc {
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      gap: 5px 0;
    }
  }
  .content {
    margin-top: 10px;
  }
  .file-content {
    padding-bottom: 50px;
    .file-box {
      .file-list {
        margin-top: 10px;
        display: flex;
        flex-direction: column;
        gap: 5px 0;
        .file-item {
          width: 600px;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          gap: 0 10px;
          .file-name {
            max-width: 400px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 12px;
            color: #333;
            cursor: pointer;
            &:hover {
              text-decoration: underline;
              color: $mainColor;
            }
          }
        }
      }
    }
  }
  ::v-deep(.el-form-item__label) {
    font-weight: 600;
  }
  .fixed-btns {
    position: fixed;
    z-index: 1;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    padding: 5px 10px;
    background: #fff;
    display: flex;
    align-items: center;
    gap: 0 10px;
  }
}
</style>